// 云函数 - 微信支付回调处理
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('收到微信支付回调:', JSON.stringify(event, null, 2))
  
  try {
    // 云开发支付回调的参数格式
    const { 
      outTradeNo,      // 商户订单号 (对应我们的wechatOrderNo)
      transactionId,   // 微信支付订单号
      resultCode,      // 支付结果
      returnCode,      // 返回状态码
      attach           // 附加数据
    } = event
    
    console.log('解析回调参数:', {
      outTradeNo,
      transactionId,
      resultCode,
      returnCode,
      attach
    })
    
    if (!outTradeNo) {
      console.error('缺少商户订单号')
      return {
        success: false,
        message: '缺少商户订单号'
      }
    }
    
    if (returnCode !== 'SUCCESS' || resultCode !== 'SUCCESS') {
      console.log('支付失败，更新状态')
      // 支付失败，更新状态
      await db.collection('activity_registrations')
        .where({ wechatOrderNo: outTradeNo })
        .update({
          data: {
            paymentStatus: 'failed',
            updatedAt: new Date()
          }
        })
      
      return {
        success: false,
        message: '支付失败'
      }
    }
    
    // 查找待支付记录
    const registrationResult = await db.collection('activity_registrations')
      .where({ wechatOrderNo: outTradeNo })
      .get()
    
    if (registrationResult.data.length === 0) {
      console.error('未找到对应的报名记录:', outTradeNo)
      return {
        success: false,
        message: '未找到对应的报名记录'
      }
    }
    
    const registration = registrationResult.data[0]
    console.log('找到报名记录:', registration._id)
    
    // 如果已经支付成功，直接返回
    if (registration.paymentStatus === 'paid') {
      console.log('支付已处理，直接返回')
      return {
        success: true,
        message: '支付已处理'
      }
    }
    
    const now = new Date()
    
    // 开始事务处理
    const transaction = await db.startTransaction()
    
    try {
      // 1. 更新报名记录为已支付
      await transaction.collection('activity_registrations')
        .doc(registration._id)
        .update({
          data: {
            paymentStatus: 'paid',
            status: 1,
            transactionId: transactionId,
            payTime: now,
            updatedAt: now
          }
        })
      
      console.log('更新报名记录为已支付:', registration._id)
      
      // 2. 获取用户信息
      const userResult = await transaction.collection('users')
        .where({ _openid: registration.registrantId })
        .get()
      
      if (userResult.data.length === 0) {
        throw new Error('用户不存在')
      }
      
      const userInfo = userResult.data[0]
      
      // 3. 返现等额金额到用户余额
      await transaction.collection('users')
        .where({ _openid: registration.registrantId })
        .update({
          data: {
            balance: db.command.inc(registration.totalAmount),
            updatedAt: now
          }
        })
      
      console.log(`返现成功：用户${registration.registrantId}余额增加¥${registration.totalAmount}`)
      
      // 4. 添加参与者到活动成员表
      const memberPromises = registration.participants.map(participant => {
        return transaction.collection('activity_members').add({
          data: {
            activityId: registration.activityId,
            registrantId: registration.registrantId,
            registrationId: registration._id,
            name: participant.name,
            phone: participant.phone,
            createdAt: now
          }
        })
      })
      
      await Promise.all(memberPromises)
      console.log(`成功添加${registration.participants.length}个参与者到活动成员表`)
      
      // 5. 更新活动参与人数
      await transaction.collection('activities')
        .doc(registration.activityId)
        .update({
          data: {
            signedUpCount: db.command.inc(registration.participants.length),
            updatedAt: now
          }
        })
      
      console.log(`活动参与人数增加${registration.participants.length}人`)
      
      // 6. 更新用户活动中继表
      const userActivityResult = await transaction.collection('user_activity_relay')
        .where({
          userId: registration.registrantId
        })
        .get()
      
      if (userActivityResult.data.length > 0) {
        const userActivity = userActivityResult.data[0]
        const activityRecords = userActivity.activityRecords || []
        activityRecords.push({
          activityId: registration.activityId,
          status: 'registered',
          registrationTime: now,
          paymentStatus: 'paid',
          registrationId: registration._id
        })
        
        await transaction.collection('user_activity_relay')
          .doc(userActivity._id)
          .update({
            data: {
              activityRecords: activityRecords,
              updatedAt: now
            }
          })
        console.log('更新用户活动中继表记录')
      } else {
        await transaction.collection('user_activity_relay').add({
          data: {
            userId: registration.registrantId,
            activityRecords: [{
              activityId: registration.activityId,
              status: 'registered',
              registrationTime: now,
              paymentStatus: 'paid',
              registrationId: registration._id
            }],
            createdAt: now,
            updatedAt: now
          }
        })
        console.log('创建新的用户活动中继表记录')
      }
      
      // 7. 提交事务
      await transaction.commit()
      
      return {
        success: true,
        message: '支付处理成功',
        data: {
          registrationId: registration._id,
          cashbackAmount: registration.totalAmount,
          newBalance: (userInfo.balance || 0) + registration.totalAmount,
          newParticipantsCount: registration.participants.length
        }
      }
      
    } catch (transactionError) {
      await transaction.rollback()
      console.error('事务处理失败:', transactionError)
      
      // 更新为失败状态
      await db.collection('activity_registrations')
        .where({ wechatOrderNo: outTradeNo })
        .update({
          data: {
            paymentStatus: 'failed',
            updatedAt: new Date()
          }
        })
      
      return {
        success: false,
        message: '支付处理失败: ' + transactionError.message
      }
    }
    
  } catch (error) {
    console.error('支付回调处理失败:', error)
    return {
      success: false,
      message: '支付回调处理失败: ' + error.message
    }
  }
}